<template>
  <div class="container">
    <!-- 页面名称 -->
    <div class="header">
      <span>系统用户</span>
    </div>

    <!-- 内容 -->
    <el-container class="body">
      <!-- 树形 -->
      <el-aside width="200px" class="mainaside">
        <div class="user_tree">
          <el-tree
            node-key="forgid"
            lazy
            accordion
            highlight-current
            :expand-on-click-node="false"
            :props="pageData.treeParams.props"
            :load="treeLoad"
            :default-expanded-keys="pageData.treeParams.defaultExpKeys"
            @current-change="onHandleTreeCurrentChange"
          >
          </el-tree>
        </div>
      </el-aside>
      <el-main class="mainmain">
        <div class="firsthe">
          <!-- 新增按钮及查询 -->
          <el-button
            type="primary"
            class="add"
            @click="onHandleAdd"
            :v-if="pageData.permissions.Add"
            >新增</el-button
          >
          <el-dialog
            :width="500"
            :title="pageData.editDialogTitle"
            v-model="pageData.editDialogVisible"
            destroy-on-close
            custom-class="editDialog-class"
          >
            <useredit
              :modifyObj="pageData.tableParams.currentRow"
              :currentOrg="pageData.treeParams.currentNode"
              :isAdd="pageData.isAdd"
              @Ok="onOk"
              @Cancel="() => (pageData.editDialogVisible = false)"
            />
          </el-dialog>

          <div class="search">
            <el-input
              v-model="pageData.queryParams.keyword"
              placeholder="请输入登录名/名称"
              clearable
              ><template #prepend>用户查询</template>
            </el-input>

            <el-button type="primary" plain @click="onHandleSearch"
              >搜索</el-button
            >
            <el-button type="warning" plain @click="onHandleReset"
              >重置</el-button
            >
          </div>
        </div>

        <el-row class="row-2">
          <!-- tabel -->
          <el-table
            ref="userTable"
            class="user-table"
            row-key="fuserid"
            stripe
            border
            highlight-current-row
            v-loading="pageData.tableParams.tableLoading"
            :data="pageData.tableParams.tableData"
            @sort-change="tableSortFunc"
          >
            <!-- @current-change="(row) => (pageData.tableParams.currentRow = row)" -->
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="60"
            >
            </el-table-column>
            <el-table-column
              prop="ffullname"
              label="用户名称"
              min-width="120"
              sortable="custom"
            >
            </el-table-column>
            <el-table-column
              prop="fusername"
              label="登录名"
              min-width="120"
              sortable="custom"
            >
            </el-table-column>
            <el-table-column
              prop="empname"
              label="职员名称"
              min-width="120"
              :formatter="empFormatter"
            >
            </el-table-column>
            <el-table-column
              prop="state"
              label="状态"
              width="60"
              align="center"
              show-overflow-tooltip
              :formatter="stateFormatter"
            >
            </el-table-column>
            <el-table-column
              prop="fcreatetime"
              label="录入时间"
              width="150"
              align="center"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              :v-if="
                pageData.permissions.Edit ||
                pageData.permissions.Del ||
                pageData.permissions.BindRole ||
                pageData.permissions.ResetPwd
              "
              label="操作"
              width="115"
              align="center"
              show-overflow-tooltip
            >
              <template #default="{ row }">
                <el-icon
                  :v-if="pageData.permissions.Edit"
                  title="编辑"
                  style="cursor: pointer; margin: 0 3px"
                  @click="onHandleEdit(row)"
                >
                  <Edit />
                </el-icon>
                <el-icon
                  :v-if="pageData.permissions.Del"
                  title="删除"
                  style="cursor: pointer; margin: 0 3px"
                  @click="onHandleDel(row.fuserid)"
                >
                  <Delete />
                </el-icon>
                <el-icon
                  :v-if="pageData.permissions.ResetPwd"
                  title="修改密码"
                  style="cursor: pointer; margin: 0 3px"
                  @click="onHandleResetPwd(row)"
                >
                  <Unlock />
                </el-icon>
                <el-icon
                  :v-if="pageData.permissions.BindRole"
                  title="绑定角色"
                  style="cursor: pointer; margin: 0 3px"
                  @click="onHandleBindRole(row)"
                >
                  <UserFilled />
                </el-icon>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页查询 -->
          <el-col :span="24">
            <el-pagination
            
              layout="total, sizes, prev, pager, next, jumper"
              :page-sizes="pageData.tableParams.pageSizeOptions"
              :current-page="pageData.queryParams.pageIndex"
              :page-size="pageData.queryParams.pageSize"
              :total="pageData.tableParams.total"
              @current-change="onHandleCurrentChange"
              @size-change="onHandleSizeChange"
              style="margin-top: 20px"
            >
            </el-pagination>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
    <!-- 修改密码 -->
    <el-dialog
      :width="360"
      :title="pageData.pwdDialogTitle"
      v-model="pageData.pwdDialogVisible"
      destroy-on-close
      custom-class="editDialog-class"
    >
      <el-form
        ref="resetPwdForm"
        class="resetPwdForm"
        :model="pageData.pwdFormData"
        :rules="pageData.pwdFormRules"
        status-icon
        label-width="100px"
      >
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="新密码：" prop="newpwd">
              <el-input
                show-password
                v-model="pageData.pwdFormData.newpwd"
                placeholder="请输入新密码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="确认密码：" prop="repwd">
              <el-input
                show-password
                v-model="pageData.pwdFormData.repwd"
                placeholder="请再次输入密码"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row>
        <el-col :span="24" style="text-align: right">
          <el-button @click="onHandleCancelResetPwd">取 消</el-button>
          <el-button
            :v-if="pageData.permissions.ResetPwd"
            type="primary"
            @click="onHandleSureResetPwd"
            >确 定</el-button
          >
        </el-col>
      </el-row>
    </el-dialog>

    <!-- 角色 -->
    <el-dialog
      :width="400"
      :title="pageData.userDialogTitle"
      v-model="pageData.userDialogVisible"
      destroy-on-close
      custom-class="editDialog-class"
    >
      <userrole
        :orgObj="pageData.treeParams.currentNode"
        :userObj="pageData.tableParams.currentRow"
        @Ok="() => (pageData.userDialogVisible = false)"
        @Cancel="() => (pageData.userDialogVisible = false)"
      />
    </el-dialog>
  </div>
</template>

<script>
// import { nextTick } from "vue";
import { onMounted, reactive, ref, toRefs } from "vue";
import { ElLoading, ElMessage, ElMessageBox } from "element-plus";
import utils from "@/common/utils";
import enums from "@/common/enums";

import {
  getOrgList,
  queryUserPageList,
  deleteUser,
  resetUserPwd,
} from "@/api/system";
import useredit from "./edit";
import userrole from "./userrole";
import { Edit, Delete, Unlock, UserFilled } from "@element-plus/icons-vue";

export default {
  name: "UserInfo",
  components: { useredit, userrole, Edit, Delete, Unlock, UserFilled },
  setup(props, context) {
    onMounted(() => {
      // nextTick(pageFunc.getTableData);
      // let st = null;
      // window.onresize = () => {
      //   return (() => {
      //     if (st) {
      //       clearTimeout(st);
      //       st = null;
      //     }
      //     st = setTimeout(() => {
      //       this.setPageHeight();
      //     }, 500);
      //   })();
      // };
    });

    const userTable = ref();
    const resetPwdForm = ref();
    const pageState = reactive({
      pageData: {
        permissions: {
          Add: utils.checkPermission("sysuser_add"),
          Del: utils.checkPermission("sysuser_delete"),
          Edit: utils.checkPermission("sysuser_edit"),
          BindRole: utils.checkPermission("sysuser_bindrole"),
          ResetPwd: utils.checkPermission("sysuser_resetpwd"),
        },
        stateEnumObj: enums.StateEnum,
        screenHeight: 0,
        treeParams: {
          props: {
            label: "fname",
            children: "children",
            isLeaf: "isleaf",
          },
          defaultExpKeys: [],
          currentNode: {},
        },
        queryParams: {
          pageIndex: 1,
          pageSize: 10,
          sortFields: "",
          sortOrder: enums.SortEnum.Asc.key,
          orgid: "",
          keyword: "",
          state: enums.StateEnum.Delete.value,
        },
        tableParams: {
          tableLoading: false,
          tableHeight: 0,
          // tableColumns: [],
          pageSizeOptions: ["10", "15", "30", "50", "100"],
          total: 0,
          tableData: [],
          multipleSelection: [],
          currentRow: {},
        },

        editDialogTitle: "用户",
        editDialogVisible: false,
        isAdd: false,
        pwdDialogTitle: "修改密码",
        pwdDialogVisible: false,
        pwdFormData: {
          userid: "",
          newpwd: "",
          repwd: "",
        },
        pwdFormRules: {
          newpwd: [{ required: true, message: "请输入密码", trigger: "blur" }],
          repwd: [
            { required: true, message: "请再次输入密码", trigger: "blur" },
          ],
        },
        userDialogTitle: "绑定角色",
        userDialogVisible: false,
      },
    });
    const pageFunc = {
      treeLoad: (node, resolve) => {
        const flag = node.level === 0;
        const orgid = flag ? "" : node.data.forgid;
        getOrgList(orgid)
          .then((ret) => {
            if (flag && ret.length > 0) {
              pageState.pageData.treeParams.defaultExpKeys = [ret[0].forgid];
            }
            resolve(ret);
          })
          .catch((error) => {
            ElMessage.error(error.message || "请求出错");
          });
      },
      getTableData: () => {
        if (utils.isEmpty(pageState.pageData.queryParams.orgid)) return;
        pageState.pageData.tableParams.currentRow = {};
        pageState.pageData.tableParams.tableLoading = true;
        queryUserPageList(pageState.pageData.queryParams)
          .then((ret) => {
            pageState.pageData.tableParams.tableData = ret.data;
            pageState.pageData.tableParams.total = ret.recordsTotal;
            pageState.pageData.tableParams.tableLoading = false;
          })
          .catch((error) => {
            ElMessage.error(error.message || "请求出错");
            pageState.pageData.tableParams.tableLoading = false;
          });
      },
      tableSortFunc: ({ column, prop, order }) => {
        pageState.pageData.queryParams.sortFields = prop;
        if (!utils.isEmpty(order) && order === "ascending") {
          pageState.pageData.queryParams.sortOrder = enums.SortEnum.Asc.key;
        } else if (!utils.isEmpty(order) && order === "descending") {
          pageState.pageData.queryParams.sortOrder = enums.SortEnum.Desc.key;
        } else {
          pageState.pageData.queryParams.sortOrder = enums.SortEnum.Asc.key;
        }
        pageFunc.getTableData();
      },
      empFormatter: (row, column, cellValue, index) => {
        if (utils.isEmpty(cellValue)) return "未绑定";
        else return cellValue;
      },
      stateFormatter: (row, column, cellValue, index) => {
        return pageState.pageData.stateEnumObj.getLabelByValue(cellValue);
      },
      onHandleTreeCurrentChange: (data) => {
        pageState.pageData.treeParams.currentNode = data;
        pageState.pageData.queryParams.keyword = "";
        pageState.pageData.queryParams.pageIndex = 1;
        pageState.pageData.queryParams.orgid = data.forgid;
        pageFunc.getTableData();
      },
      onHandleCurrentChange: (e) => {
        pageState.pageData.queryParams.pageIndex = e;
        pageFunc.getTableData();
      },
      onHandleSizeChange: (e) => {
        pageState.pageData.queryParams.pageIndex = 1;
        pageState.pageData.queryParams.pageSize = e;
        pageFunc.getTableData();
      },
      // 模糊查询
      onHandleSearch: () => {
        pageFunc.getTableData();
      },
      onHandleReset: () => {
        pageState.pageData.queryParams.keyword = "";
        pageFunc.getTableData();
      },
      onHandleKeywordBlur: () => {
        pageState.pageData.queryParams.pageIndex = 1;
        pageFunc.getTableData();
      },
      onHandleAdd: () => {
        if (utils.isEmpty(pageState.pageData.treeParams.currentNode)) {
          ElMessage.warning("请选中需要添加用户的机构");
          return;
        }
        pageState.pageData.editDialogTitle = "新增";
        pageState.pageData.editDialogVisible = true;
        pageState.pageData.isAdd = true;
      },
      onHandleEdit: (row) => {
        if (utils.isEmpty(row)) {
          ElMessage.warning("请选中需要操作的数据行");
          return;
        }
        pageState.pageData.tableParams.currentRow = row;
        pageState.pageData.editDialogTitle = "编辑";
        pageState.pageData.editDialogVisible = true;
        pageState.pageData.isAdd = false;
      },
      onHandleDel: (id) => {
        if (utils.isEmpty(id)) {
          ElMessage.warning("请选中需要操作的数据行");
          return;
        }
        ElMessageBox.confirm("此操作将删除该用户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            const loading = ElLoading.service({
              lock: true,
              background: "rgba(0, 0, 0, 0.7)",
            });
            deleteUser(id)
              .then(() => {
                loading.close();
                ElMessage.success("删除成功");
                pageFunc.getTableData();
              })
              .catch((error) => {
                loading.close();
                ElMessage.error(error.message || "请求出错");
              });
          })
          .catch(() => {});
      },
      onOk: ({ isAdd, retObj }) => {
        pageState.pageData.isAdd = isAdd;
        pageState.pageData.editDialogVisible = false;
        pageFunc.getTableData();
      },
      onHandleResetPwd: (row) => {
        if (utils.isEmpty(pageState.pageData.treeParams.currentNode)) {
          ElMessage.warning("请选中需要操作的用户机构");
          return;
        }
        if (utils.isEmpty(row)) {
          ElMessage.warning("请选中需要操作的数据行");
          return;
        }
        pageState.pageData.pwdFormData.userid = row.fuserid;
        pageState.pageData.pwdDialogTitle = "修改密码";
        pageState.pageData.pwdDialogVisible = true;
      },
      onHandleCancelResetPwd: () => {
        resetPwdForm.value?.resetFields();
        pageState.pageData.pwdDialogVisible = false;
      },
      onHandleSureResetPwd: () => {
        resetPwdForm.value?.validate((valid) => {
          if (valid) {
            if (
              pageState.pageData.pwdFormData.newpwd !==
              pageState.pageData.pwdFormData.repwd
            ) {
              ElMessage.error("两次输入密码不一致");
              return;
            }
            const loading = ElLoading.service({
              lock: true,
              background: "rgba(0, 0, 0, 0.7)",
            });
            resetUserPwd(pageState.pageData.pwdFormData)
              .then(() => {
                loading.close();
                resetPwdForm.value?.resetFields();
                pageState.pageData.pwdDialogVisible = false;
                pageFunc.getTableData();
              })
              .catch((error) => {
                loading.close();
                ElMessage.error(error.message || "请求出错");
              });
          } else return false;
        });
      },
      onHandleBindRole: (row) => {
        if (utils.isEmpty(pageState.pageData.treeParams.currentNode)) {
          ElMessage.warning("请选中需要操作的用户机构");
          return;
        }
        if (utils.isEmpty(row)) {
          ElMessage.warning("请选中需要操作的数据行");
          return;
        }
        pageState.pageData.tableParams.currentRow = row;
        pageState.pageData.userDialogTitle = "绑定角色";
        pageState.pageData.userDialogVisible = true;
      },
    };

    return {
      userTable,
      resetPwdForm,
      ...toRefs(pageState),
      ...pageFunc,
    };
  },
};
</script>
<style lang="scss" scoped>
.container {
  padding: 0;
  margin: 0;
  .header {
    width: 100%;
    background-color: white;
    user-select: none;

    text-align: left;
    span {
      line-height: 50px;
      font-size: 18px;
      font-weight: 700;
      text-align: left;
      margin-left: 20px;
    }
  }

  .body {
    margin-top: 20px;
    background-color: white;
    height: 77vh;
    // 树形下拉框
    .mainaside {
      background-color: rgb(230, 240, 250);
      border-right: 1px solid #ccc;
      .user_tree {
        .el-tree {
          border-bottom: 1px solid #ddd;
        }
      }
    }
    // 内容表格
    .mainmain {
      .firsthe {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;

        .search {
          display: flex;
          align-items: center;
          user-select: none;

          .el-input {
            margin-right: 20px;
          }
        }
      }
    }
  }
}
</style>

<style>
.el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  user-select: none;
}

.el-dialog .el-dialog__body {
  flex: 1;
  overflow: auto;
}
.el-dialog .el-dialog__header {
  padding: 20px 0;
  padding-left: 20px;
  margin: 0;

  word-break: break-all;
  border-bottom: 1px solid #ddd;
  text-align: left;
}

.el-select {
  width: 100%;
  border: none;
  border-radius: 0;
}
.el-select .el-option {
  width: 100%;
  border: none;
  border-radius: 0;
}
</style>
